﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.UI.WebControls;
using negocio.servicios;
using negocio.entidades;
using dao.daos;

namespace Swimmers.form
{
    public partial class Index : System.Web.UI.Page
    {
        private enum State { Agregar, Editar, Ver }

        private ClubService clubService = new ClubService();
        private BarrioService barrioService = new BarrioService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                panelGrilla.Visible = true;
                panelFormulario.Visible = false;
                CargarCombos();
                CargarGrilla();
            }
        }

        private void CargarGrilla()
        {
            gvClubes.DataSource = clubService.ObtenerTodo(); ;
            string[] keys = new string[1];
            keys[0] = "id_club";
            gvClubes.DataKeyNames = keys;
            gvClubes.DataBind();
        }

        protected void cmdAgregar_Click(object sender, EventArgs e)
        {
            Session["estado"] = State.Agregar;
            panelFormulario.Visible = true;
            panelGrilla.Visible = false;
            if (!txtRazonSocial.Enabled)
            {
                HabilitarCampos();
                btnAceptar.Visible = true;
                btnCancelar.Text = "Cancelar";
            }
            
            panelID.Visible = true;
            LimpiarCampos();
            txtID.Enabled = false;
            txtID.Text = clubService.obtenerNuevoId().ToString();
            txtFechaAlta.Text = DateTime.Today.ToShortDateString();
            txtFechaAlta.ReadOnly = true;
        }

        private void HabilitarCampos()
        {
            txtRazonSocial.Enabled = true;
            txtDireccion.Enabled = true;
            txtCPostal.Enabled = true;
            txtEmail.Enabled = true;
            txtTelefono.Enabled = true;
            cmbBarrio.Enabled = true;
            txtTelefono.Enabled = true;
            txtFechaAlta.Enabled = true;
        }

        private void LimpiarCampos()
        {
            txtID.Text = "";
            txtRazonSocial.Text = "";
            txtDireccion.Text = "";
            txtCPostal.Text = "";
            txtEmail.Text = "";
            txtTelefono.Text = "";
            cmbBarrio.ClearSelection();
            txtTelefono.Text = "";
            txtFechaAlta.Text = "";
            gvClubes.SelectedIndex = -1;
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            panelFormulario.Visible = false;
            panelGrilla.Visible = true;
            panelID.Visible = true;
            LimpiarCampos();
        }

        protected void btnAceptar_Click(object sender, EventArgs e)
        {
            Guardar();
            panelFormulario.Visible = false;
            panelGrilla.Visible = true;
                
        }

        private void Guardar()
        {
            if (Page.IsValid)
            {
                if ((State)Session["estado"] == State.Agregar)
                {
                    clubService.Insertar(MapFormToClub());

                    //if (!proveedorService.existePorCampoNoPk(MapFormToProveedores()))
                    //if (!clubService.ExistePorCampoNoPk("clubes", "id", MapFormToClub().Id.ToString()))
                    //{
                        
                    //}
                    //else
                    //{
                    //    Show("El club ingresado existe en el sistema");
                    //}
                }
                else if ((State)Session["estado"] == State.Editar)
                {
                    clubService.Modificar(MapFormToClub());
                }
            }
            CargarGrilla();
        }

        private static void Show(string message)
        {
            string cleanMessage = message.Replace("'", "\'");
            Page page = HttpContext.Current.CurrentHandler as Page;
            string script = string.Format("alert('{0}');", cleanMessage);
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
            {
                page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true);
            }
        }

        private void CargarCombos()
        {
            cmbBarrio.DataSource = barrioService.ObtenerTodo();
            cmbBarrio.DataTextField = "Nombre";
            cmbBarrio.DataValueField = "Id";
            cmbBarrio.DataBind();
            cmbBarrio.SelectedIndex = -1;
            cmbBarrio.Items.Insert(0, " ");
        }

        private Club MapFormToClub()
        {
            Club club = new Club();
            ClubDao dao = new ClubDao();

            club.Id = Int32.Parse(txtID.Text);
            club.RazonSocial = txtRazonSocial.Text;
            club.FechaFundacion = DateTime.Parse(txtFechaAlta.Text);
            club.Direccion = txtDireccion.Text;
            club.CodigoPostal = Convert.ToInt32(txtCPostal.Text);
            club.Email = txtEmail.Text;
            if (cbIsPrivado.Checked)
            {
                club.IsPrivado = 1;
            }
            else
            {
                club.IsPrivado = 0;
            }
            club.Telefono = txtTelefono.Text;
            club.IdBarrio = Convert.ToInt32(cmbBarrio.SelectedValue);
            return club;
        }

        protected void cmdEliminar_Click(object sender, EventArgs e)
        {
            clubService.Eliminar(Convert.ToInt32(gvClubes.SelectedValue));
            CargarGrilla();
            panelFormulario.Visible = false;
            panelGrilla.Visible = true;
            
        }

        protected void cmdEditar_Click(object sender, EventArgs e)
        {
            Session["estado"] = State.Editar;
            panelFormulario.Visible = true;
            panelGrilla.Visible = false;
            Club club = clubService.ObtenerPorId(Convert.ToInt32(gvClubes.SelectedValue));
            MapClubToForm(club);
        }


        private void MapClubToForm(Club club)
        {
            if(Session["estado"].Equals(State.Editar))
            {
                txtID.Enabled = false;
            }
            txtID.Text = club.Id.ToString();
            txtRazonSocial.Text = club.RazonSocial;
            txtFechaAlta.Text = club.FechaFundacion.ToShortDateString();
            txtDireccion.Text = club.Direccion;
            txtTelefono.Text = club.Telefono;
            txtCPostal.Text = club.CodigoPostal.ToString();
            txtEmail.Text = club.Email;
            cmbBarrio.SelectedValue = club.IdBarrio.ToString();
            if (club.IsPrivado == 0)
            {
                cbIsPrivado.Checked = false;
            }
            else
            {
                cbIsPrivado.Checked = true;
            }

        }

        protected void cmdRecargarGrilla_Click(object sender, EventArgs e)
        {
            txtRazonSocialBuscar.Text = "";
        }

        protected void cmdBuscarRazonSocial_Click(object sender, EventArgs e)
        {
            if (txtRazonSocialBuscar.Text.Length != 0)
            {
                gvClubes.DataSource = clubService.Buscar(txtRazonSocialBuscar.Text);
                gvClubes.DataBind();
            }
            
        }

        protected void gvClubes_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[0].Text = "Seleccionar";
                e.Row.Cells[1].Text = "ID Club";
                e.Row.Cells[2].Text = "Razón Social";
                e.Row.Cells[3].Text = "Direccion";
                e.Row.Cells[4].Text = "Código Postal";
                e.Row.Cells[5].Text = "Mail";
                e.Row.Cells[6].Text = "Telefono";
                e.Row.Cells[7].Text = "Barrio";
                e.Row.Cells[8].Text = "Privado";
                e.Row.Cells[9].Text = "Fecha de fundación";
            }
        }


    }
}